<?php
/**
 * @package		简易CMS
 * @subpackage	插件函数包
 * @version		$Id: function_portal.php 29 2013-05-07 06:45:56Z hopingsoft@gmail.com $
 * @author		Hoping
 * @copyright	Copyright (C) 2010 Hoping Software Studio.
 */

function pic_get($filepath, $type, $thumb, $remote, $return_thumb=1) {
	global $_G;

	$url = $filepath;
	if($return_thumb && $thumb) $url .= '.thumb.jpg';
	return ($remote?$_G['setting']['ftp']['attachurl']:$_G['setting']['attachurl']).$type.'/'.$url;
}

function category_remake($catid) {
	global $_G;

	$cat = $_G['cache']['portalcategory'][$catid];
	if(empty($cat)) return array();

	foreach ($_G['cache']['portalcategory'] as $value) {
		if($value['catid'] == $cat['upid']) {
			$cat['ups'][$value['catid']] = $value;
			$upid = $value['catid'];
			while(!empty($upid)) {
				if(!empty($_G['cache']['portalcategory'][$upid]['upid'])) {
					$upid = $_G['cache']['portalcategory'][$upid]['upid'];
					$cat['ups'][$upid] = $_G['cache']['portalcategory'][$upid];
				} else {
					$upid = 0;
				}
			}
		} elseif($value['upid'] == $cat['catid']) {
			$cat['subs'][$value['catid']] = $value;
		} elseif($value['upid'] == $cat['upid']) {
			$cat['others'][$value['catid']] = $value;
		}
	}
	if(!empty($cat['ups'])) $cat['ups'] = array_reverse($cat['ups'], TRUE);
	return $cat;
}

function getportalcategoryurl($catid) {
	if(empty($catid)) return '';
	loadcache('portalcategory');
	$portalcategory = getglobal('cache/portalcategory');
	if($portalcategory[$catid]) {
		return $portalcategory[$catid]['caturl'];
	} else {
		return '';
	}
}

function blog_bbcode($message) {
	$message = preg_replace("/\[flash\=?(media|real)*\](.+?)\[\/flash\]/ie", "blog_flash('\\2', '\\1')", $message);
	return $message;
}
function blog_flash($swf_url, $type='') {
	$width = '520';
	$height = '390';
	if ($type == 'media') {
		$html = '<object classid="clsid:6bf52a52-394a-11d3-b153-00c04f79faa6" width="'.$width.'" height="'.$height.'">
			<param name="autostart" value="0">
			<param name="url" value="'.$swf_url.'">
			<embed autostart="false" src="'.$swf_url.'" type="video/x-ms-wmv" width="'.$width.'" height="'.$height.'" controls="imagewindow" console="cons"></embed>
			</object>';
	} elseif ($type == 'real') {
		$html = '<object classid="clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa" width="'.$width.'" height="'.$height.'">
			<param name="autostart" value="0">
			<param name="src" value="'.$swf_url.'">
			<param name="controls" value="Imagewindow,controlpanel">
			<param name="console" value="cons">
			<embed autostart="false" src="'.$swf_url.'" type="audio/x-pn-realaudio-plugin" width="'.$width.'" height="'.$height.'" controls="controlpanel" console="cons"></embed>
			</object>';
	} else {
		$html = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="'.$width.'" height="'.$height.'">
			<param name="movie" value="'.$swf_url.'">
			<param name="allowscriptaccess" value="none">
			<param name="allowNetworking" value="none">
			<embed src="'.$swf_url.'" type="application/x-shockwave-flash" width="'.$width.'" height="'.$height.'" allowfullscreen="true" allowscriptaccess="always"></embed>
			</object>';
	}
	return $html;
}

function category_get_wheresql($cat) {
	$wheresql = '';
	if(is_array($cat)) {
		$catid = $cat['catid'];
		if(!empty($cat['subs'])) {
			include_once libfile('function/portalcp');
			$subcatids = category_get_childids('portal', $catid);
			$subcatids[] = $catid;

			$wheresql = "at.catid IN (".dimplode($subcatids).")";
		} else {
			$wheresql = "at.catid='$catid'";
		}
	}
	$wheresql .= " AND at.status='0'";
	return $wheresql;
}

function category_get_list($cat, $wheresql, $page = 1, $perpage = 10) {
	global $_G;
	$start = ($page-1)*$perpage;
	if($start<0) $start = 0;
	$list = array();
	$pricount = 0;
	$multi = '';
	$count = DB::result(DB::query("SELECT COUNT(*) FROM #__portal_article_title at WHERE $wheresql"), 0);
	if($count) {
		$query = DB::query("SELECT * FROM #__portal_article_title at WHERE $wheresql ORDER BY at.dateline DESC LIMIT $start,$perpage");
		while ($value = DB::fetch($query)) {
			$value['catname'] = $value['catid'] == $cat['catid'] ? $cat['catname'] : $_G['cache']['portalcategory'][$value['catid']]['catname'];
			if($value['pic']) {
				$value['pic'] = pic_get($value['pic'], 'portal', $value['thumb'], $value['remote']);
			}
			$value['url'] = 'index.php?task=view&aid='.$value['aid'];
			$value['dateline'] = dgmdate($value['dateline']);
			if($value['status'] == 0 || $value['uid'] == $_G['uid'] || $_G['adminid'] == 1) {
				$list[] = $value;
			} else {
				$pricount++;
			}
		}
		$multi = multi($count, $perpage, $page, $cat['caturl']);
	}
	return $return = array('list'=>$list,'count'=>$count,'multi'=>$multi,'pricount'=>$pricount);
}

function category_get_list_more($cat, $wheresql, $hassub = true,$hasnew = true,$hashot = true) {
	global $_G;
	$data = array();
	$catid = $cat['catid'];

	$cachearr = array();
	if($hashot) $cachearr[] = 'portalhotarticle';
	if($hasnew) $cachearr[] = 'portalnewarticle';

	if($hassub) {
		foreach((array)$cat['children'] as $childid) {
			$cachearr[] = 'subcate'.$childid;
		}
	}

	foreach ($cachearr as $key) {
		$cachekey = $key.$catid;
		$data[$key] = '';
			$list = array();
			$sql = '';
			if($key == 'portalhotarticle') {
				$dateline = TIMESTAMP - 3600 * 24 * 90;
				$sql = "SELECT at.* FROM #__portal_article_title at WHERE $wheresql ORDER BY at.viewnum DESC LIMIT 10";
			} elseif($key == 'portalnewarticle') {
				$sql = "SELECT * FROM #__portal_article_title at WHERE $wheresql ORDER BY at.dateline DESC LIMIT 10";
			} elseif(substr($key, 0, 7) == 'subcate') {
				$cacheid = intval(str_replace('subcate', '', $key));
				if(!empty($_G['cache']['portalcategory'][$cacheid])) {
					$where = '';
					if(!empty($_G['cache']['portalcategory'][$cacheid]['children']) && dimplode($_G['cache']['portalcategory'][$cacheid]['children'])) {
						$_G['cache']['portalcategory'][$cacheid]['children'][] = $cacheid;
						$where = 'at.catid IN ('.dimplode($_G['cache']['portalcategory'][$cacheid]['children']).')';
					} else {
						$where = 'at.catid='.$cacheid;
					}
					$where .= " AND at.status='0'";
					$sql = "SELECT * FROM #__portal_article_title at WHERE $where ORDER BY at.dateline DESC LIMIT 10";
				}
			}

			if($sql) {
				$query = DB::query($sql);

				while ($value = DB::fetch($query)) {
					$value['catname'] = $value['catid'] == $cat['catid'] ? $cat['catname'] : $_G['cache']['portalcategory'][$value['catid']]['catname'];
					if($value['pic']) $value['pic'] = pic_get($value['pic'], 'portal', $value['thumb'], $value['remote']);
					$value['timestamp'] = $value['dateline'];
					$value['dateline'] = dgmdate($value['dateline']);
					$list[] = $value;
				}
			}

			$data[$key] = $list;

	}
	return $data;
}

function getremotefile($file) {
	global $_G;
	@set_time_limit(0);
	if(!@readfile($_G['setting']['ftp']['attachurl'].'portal/'.$file)) {
		require_once libfile('class/ftp');

		$ftp = new cmsFTP();
		if(!($_G['setting']['ftp']['connid'] = $ftp->connect())) {
			return FALSE;
		}
		$tmpfile = @tempnam($_G['setting']['attachdir'], '');
		if($ftp->ftp_get($_G['setting']['ftp']['connid'], $tmpfile, $file, FTP_BINARY)) {
			@readfile($tmpfile);
			@unlink($tmpfile);
		} else {
			@unlink($tmpfile);
			return FALSE;
		}
	}
	return TRUE;
}

function getlocalfile($filename, $readmod = 2, $range = 0) {
	if($readmod == 1 || $readmod == 3 || $readmod == 4) {
		if($fp = @fopen($filename, 'rb')) {
			@fseek($fp, $range);
			if(function_exists('fpassthru') && ($readmod == 3 || $readmod == 4)) {
				@fpassthru($fp);
			} else {
				echo @fread($fp, filesize($filename));
			}
		}
		@fclose($fp);
	} else {
		@readfile($filename);
	}
	@flush();
	@ob_flush();
}

function CheckMod(){
	global $_G, $modesession, $navtitle;
	define('CURMODULE', 'portalcp');
	if (!$_G['inajax'] && ($_G['group']['allowmanagearticle'] || $_G['group']['allowauthorizedarticle'] || $_G['group']['allowauthorizedblock'] || $_G['group']['allowdiy'])) {
		require_once libfile('class/panel');
		$modsession = new ControlPanel(PORTALCP_PANEL);
		if(getgpc('login_panel') && getgpc('cppwd') && submitcheck('submit')) {
			$modsession->dologin($_G[uid], getgpc('cppwd'), true);
		}
		if(!$modsession->islogin) {
			include template('portalcp/login');
			dexit();
		}
	}
	$navtitle = lang('core', 'Portal management');
	require_once libfile('function/portalcp');
}




function portal_upload_error($msg) {
	echo '<script>';
	echo 'if(parent.$$$(\'localfile_'.$_GET['attach_target_id'].'\') != null)parent.$$$(\'localfile_'.$_GET['attach_target_id'].'\').innerHTML = \''.lang('portalcp', 'upload_error').$msg.'\';else alert(\''.$msg.'\')';
	echo '</script>';
	exit();
}

function portal_upload_show($attach) {

	$imagehtml = $filehtml = '';

	if($attach['isimage']) {
		$imagehtml = get_uploadcontent($attach);
	} else {
		$filehtml = get_uploadcontent($attach);
	}

	echo '<script>';
	if($imagehtml) echo 'parent.$$$(\'attach_image_body\').innerHTML += \''.addslashes($imagehtml).'\';';
	if($filehtml) echo 'parent.$$$(\'attach_file_body\').innerHTML += \''.addslashes($filehtml).'\';';

	echo 'if(parent.$$$(\'localfile_'.$_GET['attach_target_id'].'\') != null)parent.$$$(\'localfile_'.$_GET['attach_target_id'].'\').style.display = \'none\';';
	echo 'parent.$$$(\'attach_ids\').value += \','.$attach['attachid'].'\';';
	echo '</script>';
}

function tpl_checkperm($tpl) {
	global $_G;
	list($file,$id) = explode(':', $tpl);
	if($file == 'portal/list'){
		$catid = max(0,intval($id));
		$category = DB::fetch_first("SELECT * FROM #__common_category WHERE catid='$catid'");
		if(empty($category)) {
			showmessage('Specified category does not exist!');
		}
		if($_G['group']['allowdiy']) return true;
	} else {
		if(!$_G['group']['allowdiy']) {
			showmessage('diy_nopermission');
		}
	}
}

function getportalcategorytplname($catid) {
	$catid = max(0,intval($catid));
	$category = DB::fetch_first("SELECT * FROM #__common_category WHERE catid='$catid'");
	return !empty($category) && !empty($category['primaltplname']) ? $category['primaltplname'] : 'portal/list';
}

function ProcessCustomField($cf, $value, &$top, &$bot){
	static $row = array();
	if(!$row) $row = array('bot'=>0, 'top'=>0);
	$html = '<th width="1%" nowrap>'.$cf['name'].':</th><td width="*">';
	switch ($cf['type']) {
		case 'url':
			$html .= '<a href="'.$value.'" target="_blank">'.$value.'</a>';
			break;
		case 'urls':
			if(is_array($value['url'])){
				$urls = $value['url'];
				$notes = $value['note'];
				$curl = count($urls)-1;
				$html .= '<ul>';
				foreach((array)$urls as $k => $url){
					$note = trim($url);
					if($note){
						if($notes[$k]) $note = $notes[$k];
						$html .= '<li><a href="'.$url.'" target="_blank">'.$note.'</a></li>';
					}
				}
				$html .='</ul>';
			} else {
				$html .= '<a href="'.$value.'" target="_blank">'.$value.'</a>';
			}
			break;
		default:
			$html .= $value;
			break;
	}
	$html .= '</td>';
	if($cf['position']){
		$row['bot'] = 1-$row['bot'];
		$html = '<tr  class="cbg'.$row['bot'].'">'.$html.'</tr>';
		$bot .= $html;
	} else {
		$row['top'] = 1-$row['top'];
		$html = '<tr class="cbg'.$row['top'].'">'.$html.'</tr>';
		$top .= $html;
	}
}